import { message } from "antd";


export default {
    namespace: 'studentManagement',
    state: {
        studentList: [
            {
                id: 1,
                name: '张三',
                age: 20,
            },
            {
                id: 2,
                name: '李四',
                age: 22,
            }
        ],
        index: 2,
    },

    subscriptions: {
        setupHistory({ dispatch, history }) {  // 监听路由变化,这时候可以做一些处理,
            // 比如说根据路由的变化来获取数据，可以使用dispatch来触发action
            // 比如说根据路由的变化来改变一些状态
            return history.listen(({ pathname, state }) => {
                if (pathname === '/studentManagement') {
                    console.log('studentManagement')
                }
            })
        },
    },

    effects: {
        *addStudent({ payload }, { call, put, select }) {
            let { studentList, index } = yield select(state => state.studentManagement);//通过select获取state中的studentList和index
            let newStudent = { ...payload, id: index + 1 };
            yield put({
                type: 'updateState',
                payload: { studentList: [...studentList, newStudent], index: index + 1 },
            });
            message.success('添加成功');
        },
        *updateStudent({ payload }, { call, put, select }) {
            let { studentList } = yield select(state => state.studentManagement);
            const newStudentList = studentList.map(item => {//通过map遍历studentList，找到id与payload.id相同的项，并更新
                if (item.id == payload.id) {
                    return { ...item, ...payload };//使用对象展开运算符，将item和payload合并成一个新的对象
                }
                return item;
            })
            yield put({
                type: 'updateState',
                payload: { studentList: newStudentList },//将新的studentList更新到state中
            })
            message.success('修改成功');
        },
        *deleteStudent({ payload }, { call, put, select }) {
            let { studentList } = yield select(state => state.studentManagement);
            const newStudentList = studentList.filter(item => item.id !== payload);
            yield put({
                type: 'updateState',
                payload: { studentList: newStudentList },
            }
            )
        }
    },
    reducers: {
        updateState(state, action) {//更新state
            return { ...state, ...action.payload };//使用对象展开运算符，将state和action.payload合并成一个新的对象,这里面的state是原来的state，action.payload是新的state
        },
    }
}